
using System;
using Habazie.kf2.Core;

namespace Habazie.kf2.Roster
{
	
	/// <summary>
	/// 	User image
	/// </summary>
	public class Avatar
	{
		private jabber.JID	m_JID;
		private bool		m_ImageLoaded = false;
		private Gdk.Pixbuf	m_Avatar	= null;
		private Gdk.Pixbuf	m_Thumb		= null;
		
		public Avatar(jabber.JID jid)
		{
			m_JID = new jabber.JID (jid.Bare);
		}
		
		
		/// <summary>
		/// 	Get or set avatar pixbuf
		/// </summary>
		public Gdk.Pixbuf Pixbuf {
			get {
				if (! m_ImageLoaded) {
					LoadImage ();
					m_ImageLoaded = true;
				}
				return m_Avatar;
			}
			
			set {
				m_Avatar = value;
				m_Thumb = m_Avatar.ScaleSimple (48, 48, Gdk.InterpType.Bilinear);
				if (m_Avatar != null) {
					m_Thumb = m_Avatar.ScaleSimple (48, 48, Gdk.InterpType.Bilinear);
					StoreImage ();
				} else {
					m_Thumb = null;
				}
				m_ImageLoaded = true;
			}
		}
		
		
		/// <summary>
		/// 	Get thumbnail of avatar
		/// </summary>
		public Gdk.Pixbuf Thumbnail {
			get {
				if (! m_ImageLoaded) {
					LoadImage ();
					m_ImageLoaded = true;
				}
				return m_Thumb;
			}
		}
				
		
		/// <summary>
		/// 	Get cached image filename
		///	</summary>
		public string FileName {
			get {
				return Util.UserFile ("avatars/" + m_JID.Bare + ".png");
			}
		}
		
		
		/// <summary>
		/// 	Thumbnail file name
		/// </summary>
		public string ThumbnailFileName {
			get {
				return Util.UserFile ("avatars-thumb/" + m_JID.Bare + ".png");
			}
		}
		
		/// <summary>
		/// 	Load cached image data
		/// </summary>
		private void LoadImage ()
		{
			try {
				m_Avatar = new Gdk.Pixbuf (this.FileName);
				m_Thumb = new Gdk.Pixbuf (this.ThumbnailFileName);
			} catch (GLib.GException) {
//				Util.ReportException (e);
				// file does not exist
			}
		}
		
		
		/// <summary>
		/// 	Cache avatar
		/// </summary>
		private void StoreImage ()
		{
			string avatars = Util.UserFile ("avatars");
			if (! System.IO.Directory.Exists (avatars))
				System.IO.Directory.CreateDirectory (avatars);
				
			string avatarst = Util.UserFile ("avatars-thumb");
			if (! System.IO.Directory.Exists (avatarst))
				System.IO.Directory.CreateDirectory (avatarst);
				
			m_Avatar.Save (FileName, "png");
			m_Thumb.Save (ThumbnailFileName, "png");
		}
	}
}
